/*  
 * i-OSGi - Tunable Bundle Isolation for OSGi
 * Copyright (C) 2011  Sven Schulz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.iosgi.util.configuration;

import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.Validate;
import org.osgi.framework.BundleContext;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Sven Schulz
 */
@Component(immediate = true)
public class Reader implements FileFilter {

	private static Dictionary<String, Object> toDictionary(final Properties p) {
		Hashtable<String, Object> d = new Hashtable<String, Object>();
		for (Entry<Object, Object> e : p.entrySet()) {
			d.put((String) e.getKey(), e.getValue());
		}
		return d;
	}

	private static final Logger LOGGER = LoggerFactory.getLogger(Reader.class);

	@Requires
	private ConfigurationAdmin configAdmin;

	private BundleContext context;

	Reader(BundleContext context) {
		this.context = context;
	}

	@Validate
	void activate() throws Exception {
		String sdir = context.getProperty("org.iosgi.util.configuration.dir");
		File dir = sdir != null ? new File(sdir) : new File("./conf/");
		dir = dir.getAbsoluteFile();
		if (!dir.isDirectory() || !dir.exists()) {
			LOGGER.warn(
					"configuration path ({}) is either not a directory or does not exist",
					dir);
			return;
		}
		List<File> cfgFiles = new LinkedList<File>();
		while (dir.exists() && !dir.equals(new File(".").getAbsoluteFile())) {
			LOGGER.debug("collecting configurations from {}",
					dir.getAbsolutePath());
			for (File f : dir.listFiles(this)) {
				cfgFiles.add(f);
			}
			dir = dir.getParentFile();
		}
		Collections.sort(cfgFiles, new Comparator<File>() {
			@Override
			public int compare(File a, File b) {
				int pa = getPriority(a), pb = getPriority(b);
				return pb - pa;
			}
		});
		LOGGER.debug("processing order is {}", cfgFiles);
		for (File f : cfgFiles) {
			process(f);
		}
	}

	private int getPriority(final File f) {
		String name = f.getName();
		String[] parts = name.split("\\.");
		try {
			return Integer.parseInt(parts[0]);
		} catch (NumberFormatException nfe) {
			return 0;
		}
	}

	private String removePriority(File f) {
		String name = f.getName();
		if (this.getPriority(f) == 0 && !name.startsWith("0")) {
			return name;
		}
		return name.substring(name.indexOf('.') + 1);
	}

	private void process(final File f) throws IOException,
			FileNotFoundException {
		LOGGER.debug("processing {}", f.getAbsolutePath());
		Properties p = new Properties();
		p.load(new FileReader(f));
		String name = this.removePriority(f);
		Configuration c = null;
		if (name.contains("-")) {
			String[] parts = name.substring(0, name.lastIndexOf('.'))
					.split("-");
			LOGGER.debug("creating factory configuration {}", parts[0]);
			c = configAdmin.createFactoryConfiguration(parts[0], null);
		} else {
			String pid = name.substring(0, name.lastIndexOf('.'));
			LOGGER.debug("creating configuration {}", pid);
			c = configAdmin.getConfiguration(pid, null);
		}
		c.update(Reader.toDictionary(p));
	}

	@Override
	public boolean accept(File pathname) {
		return pathname.isFile() && pathname.getName().endsWith(".cfg");
	}

}